import json
import random

from django.http import HttpResponse, JsonResponse
from django.shortcuts import render


from django.views import View
from django_redis import get_redis_connection
from ihome.libs.captcha.captcha import captcha
from ihome.libs.yuntongxun.ccp_sms import CCP

# 获取日志器
import logging
logger = logging.getLogger('django')


# /api/v1.0/imagecode
class ImageCodeView(View):
    def get(self, request):
        """获取图片验证码数据"""
        # ① 生成图片验证码数据
        uuid = request.GET.get('cur')
        text, image = captcha.generate_captcha()

        # ② 将图片验证码存储到redis数据库
        redis_conn = get_redis_connection('verify_code')
        redis_conn.set('img_%s' % uuid, text, 300)

        # ③ 返回验证码图片数据
        return HttpResponse(image, content_type='image/jpg')


# /api/v1.0/sms/
class SMSCodeView(View):
    def post(self, request):
        """获取短信验证码"""
        # ① 接收参数并进行校验
        req_data = json.loads(request.body)
        mobile = req_data.get('mobile')
        id = req_data.get('id')
        text = req_data.get('text')

        if not all([mobile, id, text]):
            return JsonResponse({'errno': 400,
                                 'errmsg': '缺少必传参数'})

        redis_conn=get_redis_connection('verify_code')

        image_code_redis=redis_conn.get('img_%s' % id)
        if image_code_redis is None:
            return JsonResponse({'errno': 400,
                                 'errmsg': '图形验证码失效'})

        # 对比图形验证码
        if text.lower() != image_code_redis.lower():
            return JsonResponse({'errno': 400,
                                 'errmsg': '输入图形验证码有误'})

            # ③ 生成保存并发送短信验证码
        sms_code='%06d' % random.randint(0, 999999)
        print('短信验证码为：%s' % sms_code)

        # 保存短信验证码
        redis_conn.set('sms_%s' % mobile, sms_code, 300)

        # 发送短信验证码
        # CCP().send_template_sms(mobile, [sms_code, 5], 1)
        # ④ 返回响应结果
        return JsonResponse({'errno': 0,
                             'errmsg': '发送短信成功'})